<?php

namespace app\admin\controller;

use app\common\lib\Util;
use app\common\model\DeliveryRule as DeliveryRuleModel;
use think\Request;

class DeliveryRule extends Base
{
    //page
    public function index(DeliveryRuleModel $model){
        $rule = $model->field('weight_rule,distance_rule,special_time_rule,max_fee')->find();
        $this->assign('rule',$rule);
        return $this->fetch();
    }
    //创建或者编辑action
    public function create(Request $request,DeliveryRuleModel $model){
        $weight_rule = [
            "weight_start_fee"=>$request->param('weight_start_fee',0),
            "weight_for_free"=>$request->param('weight_for_free',0),
            "weight_over_start_range"=>$request->param('weight_over_start_range',0),
            "weight_over_start_perfee"=>$request->param('weight_over_start_perfee',0),
            "weight_over_second"=>$request->param('weight_over_second',0),
            "weight_max_limit"=>$request->param('weight_max_limit',0),
            "weight_fixed_fee"=>$request->param('weight_fixed_fee',0),
        ] ;
        $distance_rule = [
            "distance_start_fee"=>$request->param('distance_start_fee',0),
            "distance_for_free"=>$request->param('distance_for_free',0),
            "distance_over_start_range"=>$request->param('distance_over_start_range',0),
            "distance_over_start_perfee"=>$request->param('distance_over_start_perfee',0),
            "distance_over_second"=>$request->param('distance_over_second',0),
           // "weight_max_limit"=>$request->param('weight_max_limit'),
            "distance_fixed_fee"=>$request->param('distance_fixed_fee',0),
        ];
        $special_time_rule = [
            "start_time_one"=>$request->param('start_time_one','00:00'),
            "end_time_one"=>$request->param('end_time_one','00:00'),
            "add_fee_one"=>$request->param('add_fee_one',0),
            "start_time_two"=>$request->param('start_time_two','00:00:00'),
            "end_time_two"=>$request->param('end_time_two',"00:00:00"),
            // "weight_max_limit"=>$request->param('weight_max_limit'),
            "add_fee_two"=>$request->param('add_fee_two',0),
        ];
        $max_fee = $request->param('max_fee');
        if(empty($max_fee)||$max_fee == '0'){
            return Util::apiResponse([],'封顶金额不能为0',-1);
        }
        $data = [
            'weight_rule'=>json_encode($weight_rule,JSON_NUMERIC_CHECK),
            'distance_rule'=>json_encode($distance_rule,JSON_NUMERIC_CHECK),
            'special_time_rule'=>json_encode($special_time_rule,JSON_NUMERIC_CHECK),
            'max_fee'=>$max_fee
        ];
        $rule = $model->field('id,weight_rule,distance_rule,special_time_rule,max_fee')->find();
        if(!$rule){
            $result = $model->save($data);
        }else{
            $result = $model->save($data,['id'=>$rule['id']]);
        }
        return Util::apiResponse(['max_fee'=>$max_fee],'',1);
    }
}
